﻿using Microsoft.WowAddonStudio.Lua.LanguageService.Model;
using Microsoft.WowAddonStudio.Lua.Loaders;
using Microsoft.WowAddonStudio.Lua.Model;
using Microsoft.WowAddonStudio.Lua.Parser;

namespace Microsoft.WowAddonStudio.Lua.LanguageService.Intellisense.Providers
{
    public class ParserDeclarationProvider : DocumentationDeclarationProvider<ParserDocumentationLoader>
    {
        private readonly DocumentationParser parser;

        public ParserDeclarationProvider(DocumentationParser parser)
            : base(new ParserDocumentationLoader(parser))
        {
            this.parser = parser;
        }

        /// <summary>
        /// Gets the active scope that should be used for resolve operations.
        /// </summary>
        protected override DocumentationScope ActiveScope
        {
            get { return (DocumentationScope)parser.Scope.FindScope(Request.Line, Request.Col); }
        }

        /// <summary>
        /// Gets the source of the declaration with the qualified name.
        /// </summary>
        /// <param name="qualifiedName"></param>
        /// <returns>
        /// An instance of the <see cref="DeclarationSource"/> class or null if no declaration source can be provided.
        /// </returns>
        protected override DeclarationSource GetDeclarationSource(QualifiedName qualifiedName)
        {
            var declaration = ActiveScope.Resolve<Declaration>(qualifiedName);
            if (declaration != null && declaration.Location != null)
            {
                return new DeclarationSource
                {
                    Uri = Request.FileName,
                    Location = declaration.Location
                };
            }

            return base.GetDeclarationSource(qualifiedName);
        }
    }
}
